package com.zhihaoliang.baseframe.db;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MediatorLiveData;

import com.zhihaoliang.baseframe.db.entity.CommentEntity;
import com.zhihaoliang.baseframe.db.entity.ProductEntity;

import java.util.List;

/**
 * 创建日期：2020-02-26
 * 描述:存储库用于处理产品和产品评论
 * 作者:支豪亮
 */
public class DataRepository {
    private static DataRepository sInstance;

    private final AppDatabase mDatabase;

    /**
     * 用于监听其他的LiveDate的变化
     */
    private MediatorLiveData<List<ProductEntity>> mObservableProducts;

    private DataRepository(final AppDatabase appDatabase) {
        mDatabase = appDatabase;

        mObservableProducts = new MediatorLiveData<>();
        mObservableProducts.addSource(mDatabase.productDao().loadAllProducts(),
                products -> {
                    if (mDatabase.getDatebaseCreated().getValue()) {
                        mObservableProducts.postValue(products);
                    }
                });
    }

    public static  DataRepository getInstance(final AppDatabase appDatabase){
        if(sInstance == null){
            synchronized (DataRepository.class){
                if(sInstance == null){
                    sInstance = new DataRepository(appDatabase);
                }
            }
        }
        return sInstance;
    }

    /***
     * 获取产品列表当产品发生变化时发出通知
     */
    public LiveData<List<ProductEntity>> getProducts(){
        return mObservableProducts;
    }

    public LiveData<ProductEntity> loadProduct(final int productId){
        return mDatabase.productDao().loadProductSync(productId);
    }

    public LiveData<List<CommentEntity>>loadComment(final int productId){
        return mDatabase.commentDao().loadComments(productId);
    }

    public LiveData<List<ProductEntity>>searchProduct(final String query){
        return mDatabase.productDao().searchAllProducts(query);
    }


}